//
//  MKNewFeatureCollectionViewController.swift
//  MKWeiBo2017
//
//  Created by nicolas on 2017/8/22.
//  Copyright © 2017年 nicolas. All rights reserved.
//

import UIKit

private let itemCount = 3
private let reuseIdentifier = "Cell"

class MKNewFeatureCollectionViewController: UICollectionViewController {
    
    private let layout = UICollectionViewFlowLayout()
    
   
    init() {
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        // 注册cell
        self.collectionView!.register(MKNewFeatureCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // 设置layout参数
        // 让cell和屏幕一样大
        layout.itemSize = UIScreen.main.bounds.size
        // 水平滚动
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal
        // 间距
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        // 取消弹簧效果
        collectionView?.bounces = false
        // 不要水平滚动条
        collectionView?.showsHorizontalScrollIndicator = false
        // 分页
        collectionView?.isPagingEnabled = true
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        return itemCount
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MKNewFeatureCollectionViewCell
        cell.index = indexPath.item
        
        return cell
    }
    
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x / scrollView.frame.width)
        // 判断是否是最后一页
        if index == itemCount - 1 {
            // 获取cell,千万不要自己去创建cell,应该拿到正在显示的cell
            let indexPath = NSIndexPath(item: index, section: 0)
            
            let cell = collectionView?.cellForItem(at: indexPath as IndexPath) as! MKNewFeatureCollectionViewCell
            
            cell.startAnimation()
        }
    }
    
    
}
